package net.sashag.nadlandroid;

import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.parse.ParsePush;
import com.parse.ParseUser;

public class NadlandroidPushChatMessage {

	private static final String NEW_MESSAGE_ACTION = "net.sashag.nadlandroid.NEW_MESSAGE_ACTION";
	
	private String apartmentId;
	private String destinationUserId;

	public NadlandroidPushChatMessage(String apartmentId, String destinationUserId) {
		this.apartmentId = apartmentId;
		this.destinationUserId = destinationUserId;
	}
	
	public static Message fromPushJson(JSONObject data) throws JSONException {
		String senderName = "<Unknown>";
		String senderEmail = "<Unknown>";
		String senderPhone = "<Unknown>";
		JSONObject sender = data.getJSONObject("from");
		if (sender.has("name")) {
			senderName = sender.getString("name");
		}
		if (sender.has("email")) {
			senderEmail = sender.getString("email");
		}
		if (sender.has("phone")) {
			senderPhone = sender.getString("phone");
		}
		String apartmentId = data.getString("apartment");
		Date sendTime = new Date(data.getLong("time"));
		Message newMessage = new Message(senderName, senderEmail, senderPhone,
				apartmentId, sendTime, null /*object id populated on save*/);
		return newMessage;
	}

	public void send() {
		try {
			JSONObject data = new JSONObject();
			data.put("action", NEW_MESSAGE_ACTION);
			JSONObject sender = new JSONObject();
			ParseUser currentUser = ParseUser.getCurrentUser();
			sender.put("name", currentUser.get("Fullname"));
			sender.put("email", currentUser.getEmail());
			sender.put("phone", currentUser.get("Phone"));
			data.put("from", sender);
			data.put("time", System.currentTimeMillis());
			data.put("apartment", apartmentId);
			ParsePush push = new ParsePush();
			push.setChannel(destinationUserId);
			push.setData(data);
			push.sendInBackground();
		} catch (JSONException e) {
			Log.w("Apartment", "JSON exception sending push: " + e.getMessage());
		}
	}

}
